﻿using Metro.AxisFromSKY.Entity;
using Metro.AxisFromSKY.Model;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Metro.AxisFromSKY.Service
{
    public class AxisService
    {
        private readonly MetroDbContext _context;

        public AxisService(MetroDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// Convert dataFromSky to dataToDatabase
        /// </summary>
        /// <param name="dataList">Orignal data From Sky</param>
        public IEnumerable<AutoAxis> ConvertData(List<Data> dataList)
        {
            if (dataList == null) return new List<AutoAxis>() { };

            var ConvertDataList = dataList.Select(data => new AutoAxis
            {
                ProjectId = data.ProjectId,
                ProjectName = data.ProjectName,
                PointName = data.Pointname,
                MeasureValue = data.MeasureValue1,
                PeriodChanges = data.Value1,
                DiffChanges = data.Value2,
                DateTime = data.DateTime,
                SensorName = data.SensorName
            });
            return ConvertDataList;
        }

        /// <summary>
        /// GroupBy PrjId --Consider Multiple Projects Condition 
        /// </summary>
        public IEnumerable<IEnumerable<AutoAxis>> GroupByProjectId(List<AutoAxis> ProjectList)
        {
            return ProjectList.GroupBy(x => x.ProjectId);
        }

        /// <summary>
        /// Duplicate data Per Project
        /// </summary>
        public void DuplicatePerProject(IEnumerable<AutoAxis> PrjItems)
        {
            var PrjId = PrjItems.First().ProjectId;
            var DateTimeList = GroupByDateTime(PrjItems.ToList()).ToList();
            DuplicateDataInDb(DateTimeList, PrjId);
        }

        /// <summary>
        /// Group By DateTime
        /// </summary>
        public IEnumerable<DateTime> GroupByDateTime(List<AutoAxis> dataList)
        {
            return dataList.GroupBy(x => x.DateTime).Select(g => g.Key).ToList();
        }

        /// <summary>
        /// Duplicate Data in DataBase
        /// </summary>
        public void DuplicateDataInDb(List<DateTime> TimeList, int PrjId)
        {
            var DbTimeList = _context.AutoAxis.GroupBy(x => x.DateTime).Select(g => g.Key).ToList();

            var CommonGroupList = DbTimeList.Intersect(TimeList);
            var CommonDataList = CommonGroupList.SelectMany(g => QueryDataFromDb(PrjId, g));

            _context.RemoveRange(CommonDataList);
            _context.SaveChanges();
        }

        /// <summary>
        /// Query data by dateTime and PrjId
        /// </summary>
        public IEnumerable<AutoAxis> QueryDataFromDb(int PrjId, DateTime DateTime)
        {
            return _context.AutoAxis
                .Where(x => x.ProjectId == PrjId && x.DateTime == DateTime)
                .Select(x => x);
        }



        ///<summary>
        ///Post to DataBase
        ///</summary>
        public int PostDataToDB(List<Data> dataList)
        {
            if (dataList.Count() == 0) return 0;
            else
            {
                try
                {
                    var ConvertDataList = ConvertData(dataList).ToList();

                    // dataFromSky groupBy prjId
                    var PrjGroup = GroupByProjectId(ConvertDataList);

                    // 对每一个Project删除数据库里日期相同的数据
                    foreach (var Prj in PrjGroup) DuplicatePerProject(Prj);

                    _context.AutoAxis.AddRange(ConvertDataList);

                    return _context.SaveChanges();
                }
                catch (Exception exc)
                {
                    throw exc;
                };
            }
        }
    }
}
